package com.lwl.Utils;

import java.util.LinkedList;

public class MyTreeNode {

    public int value;

    public MyTreeNode left;

    public MyTreeNode right;

    public MyTreeNode() {
    }

    public MyTreeNode(int value) {
        this.value = value;
    }

    public MyTreeNode(int value, MyTreeNode left, MyTreeNode right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }

    /**
     * 先序遍历
     */
    public void traverseFirstBinaryTree() {
        LinkedList<MyTreeNode> stack = new LinkedList<>();
        stack.addLast(this);
        while (!stack.isEmpty()) {
            MyTreeNode node = stack.pollLast();
            System.out.print(node.value + " ,");
            if (node.right != null) {
                stack.addLast(node.right);
            }
            if (node.left != null) {
                stack.addLast(node.left);
            }
            System.out.println();
        }
    }

    /**
     * 中序遍历
     */
    public void traverseMidBinaryTree() {
        LinkedList<MyTreeNode> stack = new LinkedList<>();
        MyTreeNode node = this;
        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.addLast(node);
                node = node.left;
            } else {
                node = stack.pollLast();
                System.out.print(node.value + " ,");
                node = node.right;
            }
            System.out.println();
        }
    }


    /**
     * 层序遍历
     */
    public void traverseLevelBinaryTree() {
        LinkedList<MyTreeNode> queue = new LinkedList<>();
        queue.addLast(this);
        while (!queue.isEmpty()) {
            MyTreeNode node = queue.pollFirst();
            System.out.print(node.value + " ,");
            if (node.left != null) {
                queue.addLast(node.left);
            }
            if (node.right != null) {
                queue.addLast(node.right);
            }
        }
        System.out.println();
    }
}